package com.pureut.production.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.*;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.system.domain.SysDocument;
import com.pureut.production.domain.system.dto.SysDocumentCheckDto;
import com.pureut.production.domain.vo.*;
import com.pureut.production.mapper.*;
import com.pureut.production.service.*;
import com.pureut.production.utils.MaxNumberUtils;
import com.pureut.system.api.*;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.BackAdjustVo;
import com.pureut.system.api.vo.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 水刺产出Service
 *
 * @author: CM
 * @date: 2023/2/20  17:21
 */
@Service
public class SpunlaceOutputServiceImpl extends ServiceImpl<SpunlaceOutputMapper, SpunlaceOutput> implements SpunlaceOutputService {

    /**
     * 水刺制令单
     */
    @Resource
    private SpunlaceOrderMapper spunlaceOrderMapper;

    /**
     * 水刺产出mapper
     */
    @Resource
    private SpunlaceOutputMapper spunlaceOutputMapper;

    /**
     * 水刺产出明细service
     */
    @Resource
    private SpunlaceOutputDetailService spunlaceOutputDetailService;

    /**
     * 水刺产出明细mapper
     */
    @Resource
    private SpunlaceOutputDetailMapper spunlaceOutputDetailMapper;

    /**
     * 仓库远程调用
     */
    @Resource
    private StorageFegin storageFegin;

    /**
     * 车间建模mapper
     */
    @Resource
    private SysShopModelingMapper sysShopModelingMapper;

    @Resource
    private CutOrdersDocumentService cutOrdersDocumentService;

    @Resource
    private CutOrdersDocumentMapper cutOrdersDocumentMapper;

    /**
     * 分切制令单Service
     */
    @Resource
    private CutOrdersDocumentDetailService cutOrdersDocumentDetailService;

    /**
     * 基础配置fegin
     */
    @Resource
    private FeignService feignService;

    /**
     * 单据配置fegin
     */
    @Resource
    private SystemDocumentFeignService systemDocumentFeignService;

    /**
     * 品质检验单据fegin
     */
    @Resource
    private QualityFeginService qualityFeginService;

    /**
     * 废料打印
     */
    @Resource
    private IWasteTubeService iWasteTubeService;

    /**
     * 水刺制令单Service
     */
    @Lazy
    @Resource
    private SpunlaceOrderService spunlaceOrderService;

    @Resource
    private SchedulingPlanFeignService schedulingPlanFeignService;

    /**
     * 班组mapper
     */
    @Resource
    private GroupManagementMapper groupManagementMapper;

    /**
     * 物料mapper
     */
    @Resource
    private MaterialFinishedMapper materialFinishedMapper;

    /**
     * 投料记录mapper
     */
    @Resource
    @Lazy
    private IFeedRecordService iFeedRecordService;


    /**
     * 新增水刺产产出列表
     *
     * @param spunlaceOutputVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(SpunlaceOutputVo spunlaceOutputVo) {
        SpunlaceOutput spunlaceOutput = new SpunlaceOutput();
        BeanUtils.copyProperties(spunlaceOutputVo, spunlaceOutput);
        spunlaceOutput.setCreateMan(SecurityUtils.getUsername());
        spunlaceOutput.setCreateTime(new Date());
        spunlaceOutput.setDeptId(SecurityUtils.getDeptId());
        return save(spunlaceOutput);
    }

    /**
     * 产出打印回显
     *
     * @param id
     * @return
     */
    @Override
    public SpunlaceOutputViewDto getView(Long id) {
        return spunlaceOutputMapper.selectPrint(id);

    }

    /**
     * 水刺产出打印
     *
     * @param spunlacePrintVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SpunlaceOrderViewDto addPrint(SpunlacePrintVo spunlacePrintVo) throws Exception {

        SpunlaceOutput spunlaceOutput = getById(spunlacePrintVo.getId());

        //生产批次号
        String scpc = feignService.splitList("SCPC");
        if (scpc == null || "".equals(scpc)) {
            throw new GlobalException("请配置生产批次号编码生成配置");
        }

        //生成产品号码
        //查询水刺明细中是否是第一条数据
        Long count = spunlaceOutputDetailMapper.selectCount(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, spunlaceOutput.getSpunlaceOrderNumber()));

        //截取制令单号前半部分
        String split = spunlaceOutput.getSpunlaceOrderNumber().replaceAll("SC", "MJ");

        String mj = "";
        if (count == 0) {
            mj = split + "-001";

        } else {
            //获取当前的最大流水号
            String maxNumber = spunlaceOutputDetailMapper.getMaxNumber(split);
            //当前最大流水号+1
            String manxNumber = MaxNumberUtils.getManxNumber(maxNumber);
            mj = split + "-" + manxNumber;
        }

        if (mj == null || "".equals(mj)) {
            throw new GlobalException("请配置产品号码编码生成配置");
        }

        //spunlaceOutputDetailVo.setProductionNumber(mj);
        SpunlaceOutputDetailVo spunlaceOutputDetailVo = new SpunlaceOutputDetailVo();
        BeanUtils.copyProperties(spunlacePrintVo, spunlaceOutputDetailVo);
        spunlaceOutputDetailVo.setProductionNumber(mj);
        spunlaceOutputDetailVo.setPrintTemplateId(spunlacePrintVo.getPrintId());
        spunlaceOutputDetailVo.setProductionStatus("1");
        spunlaceOutputDetailVo.setProductionLineCode(spunlacePrintVo.getProductionLineCode());

        //获取当前用户名称
        String username = SecurityUtils.getUsername();

        List<GroupManagement> groupManagementList = groupManagementMapper.selectGroupManagement();

        for (GroupManagement management : groupManagementList) {
            if (username.equals(management.getGroupMonitorName())) {
                spunlaceOutputDetailVo.setGroupCode(management.getGroupCode());
            }

            if (management.getGroupMember().contains(username)) {
                spunlaceOutputDetailVo.setGroupCode(management.getGroupCode());
            }
        }


        //获取跨天时间和班次
        AjaxResult ajaxResult = schedulingPlanFeignService.selectShiftLine(spunlaceOutput.getProductionLine());

        if (ajaxResult == null) {
            throw new GlobalException("请配置工厂日历");
        }

        List<CalendarTeamDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), CalendarTeamDto.class);

        Date crossSkyTime = null;
        String classDifference = null;
        for (CalendarTeamDto entity : data) {

            Date nowTime = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTime);
            Date time = calendar.getTime();
            //判断当前时间是否在开始时间和结束时间之内
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            String time2 = simpleDateFormat.format(time);
            String time3 = entity.getTeamStartTime();
            String time4 = entity.getTeamEndTime();
            if (time2.compareTo(time3) > 0 && time2.compareTo(time4) < 0) {
                //获取班组
                classDifference = entity.getTeamInfo();
                //判断是否跨天,并判断当前时间小于开始时间
                if (1 == (entity.getTeamTranssky()) && time2.compareTo(time3) < 0) {
                    //如果跨天就取前一天
                    Date date = new Date();
                    //得到日历
                    Calendar calendar1 = Calendar.getInstance();
                    //把当前时间赋给日历
                    calendar1.setTime(date);
                    //设置为前一天
                    calendar1.add(Calendar.DAY_OF_MONTH, -1);
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sf.format(calendar1.getTime());
                    //得到前一天的时间
                    crossSkyTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
                } else {
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sf.format(new Date());
                    crossSkyTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
                }
            }
        }

        if (crossSkyTime == null && classDifference == null) {
            throw new GlobalException("请先配置工厂日历");
        }
        //设置班次
        spunlaceOutputDetailVo.setClasses(classDifference);

        //设置跨天时间
        spunlaceOutputDetailVo.setCrossSkyTime(crossSkyTime);
        spunlaceOutputDetailVo.setId(null);

        //生产状态
        List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //设置生产批次号
        spunlaceOutputDetailVo.setProductionBatch(scpc + classMap.get(classDifference));
        //spunlaceOutputDetailVo.setCheckStatus("1");
        boolean add = spunlaceOutputDetailService.add(spunlaceOutputDetailVo);
        if (add) {

            SpunlaceOutputDto spunlaceOutputDto = spunlaceOutputMapper.selectViewId(spunlaceOutputDetailVo.getId());

            //获取制令单号
            String moNumber = spunlacePrintVo.getSpunlaceOrderNumber();
            //通过制令单查出水刺指令单
            SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectOne(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getSpunlaceOrderNumber, moNumber));
            //查询当前制令单对应的母卷明细
            SpunlaceOutputDetail spunlaceOutputDetail = spunlaceOutputDetailMapper.selectOne(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getProductionNumber, spunlaceOutputDetailVo.getProductionNumber()).eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, moNumber));

            //判断当前制令单号下有几条明细
            Long aLong1 = spunlaceOutputDetailMapper.selectCount(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, moNumber));
            if (aLong1 == 1) {
                //修改水刺制令单下明细的第一卷标识
                spunlaceOutputDetail.setFirstNum("1");
                spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
            }

            //首检
            //获取菜单id
            Long menuId = feignService.getIdByMenuName("水刺产出");
            //交接方式
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);

            if (infoDocumentConfigById != null) {

                SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);


                if (sysDocument.getDocInspectionMark() == 1) {

                    //获取品质检验配置明细
                    List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();

                    List<SysDocumentCheckDto> documentCheckDtos1 = new ArrayList<>();
                    for (SysDocumentCheckDto sysDocumentCheckDto : documentCheckDtoList) {
                        if (sysDocumentCheckDto.getCheckSubmit() == 2 && sysDocumentCheckDto.getCheckType() == 3) {
                            documentCheckDtos1.add(sysDocumentCheckDto);
                        }
                    }
                    if (documentCheckDtoList.size() == 0) {
                        throw new GlobalException("请先配置送检类型");
                    }

                    String jydj = "FAI-" + feignService.splitList("JYDJ");
                    //取出第一个品质检验配置
                    for (SysDocumentCheckDto sysDocumentCheckDto : documentCheckDtos1) {

                        //如果是批次检
                        if (sysDocumentCheckDto.getCheckMode() == 2) {

                            //查询当前批次下有几条明细
                            long aLong = spunlaceOutputDetailMapper.selectCount(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getProductionBatch, spunlaceOutputDetail.getProductionBatch()).eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, moNumber));

                            if (aLong == 1) {
                                //生成品质检验单
                                QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();

                                qualityInspectionDocumentVo.setItemRank(2);//检测阶别：2:Fai
                                qualityInspectionDocumentVo.setInspectionSheetNo(jydj);//检测单号
                                qualityInspectionDocumentVo.setCategory(4);//类别：成品
                                qualityInspectionDocumentVo.setProductionLine(spunlaceOrder.getProductionLine());//线别

                                qualityInspectionDocumentVo.setMaterialCode(spunlaceOrder.getMaterialCode());
                                qualityInspectionDocumentVo.setMaterialCategory(Long.parseLong(spunlaceOutputDto.getMaterialType() + ""));//物料类别
                                qualityInspectionDocumentVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());//批次号

                                qualityInspectionDocumentVo.setAssociatedNo(moNumber);//关联单号
                                qualityInspectionDocumentVo.setDifferentString(spunlaceOrder.getCustomerCode());//客户

                                qualityInspectionDocumentVo.setClasses(spunlaceOutputDetail.getClasses());//班次
                                qualityInspectionDocumentVo.setGroupCode(spunlaceOutputDetail.getGroupCode());//班组
                                qualityInspectionDocumentVo.setCrossSkyTime(spunlaceOutputDetail.getCrossSkyTime());//跨天时间
                                qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                qualityInspectionDocumentVo.setModeType(9);

                                List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<MaterialNumberAndBatchNoVo>();

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(spunlaceOutputDetail.getProductionNumber());
                                materialNumberAndBatchNoVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());
                                materialNumberAndBatchNoVo.setMaterialCategory(spunlaceOutputDto.getMaterialType());
                                materialNumberAndBatchNoVo.setWsiCustomCode(spunlaceOrder.getCustomerCode());
                                materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                                qualityFeginService.add(qualityInspectionDocumentVo);

                                //修改水刺明细关联单号，送检标识,检验状态为待检验
                                spunlaceOutputDetail.setIsFlag("1");//检验标识
                                spunlaceOutputDetail.setCheckStatus("1");//待检验
                                spunlaceOutputDetail.setConnectQualityDoc(jydj);
                                spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
                            } else {
                                //查询最近一条品质检验单号并且有检验标识
                                //SpunlaceOutputDetailDto spunlaceOutputDetailDto = spunlaceOutputDetailMapper.selectQuality(moNumber);
                                SpunlaceOutputDetailDto spunlaceOutputDetailDto = spunlaceOutputDetailMapper.selectPiciQuality(moNumber, spunlaceOutputDetail.getProductionBatch());
                                QualityTemporaryVo qualityTemporaryVo = new QualityTemporaryVo();
                                qualityTemporaryVo.setMaterialNumber(mj);
                                qualityTemporaryVo.setInspectionSheetNo(spunlaceOutputDetailDto.getConnectQualityDoc());
                                qualityTemporaryVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());
                                qualityTemporaryVo.setMaterialCode(spunlaceOrder.getMaterialCode());
                                qualityFeginService.materialAdd(qualityTemporaryVo);

                                spunlaceOutputDetail.setConnectQualityDoc(spunlaceOutputDetailDto.getConnectQualityDoc());
                                spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
                            }
                        } /*else if (sysDocumentCheckDto.getCheckMode() == 1) {
                    //查询最近一条品质检验单号并且有检验标识
                    SpunlaceOutputDetailDto spunlaceOutputDetailDto = spunlaceOutputDetailMapper.selectQuality(moNumber);
                    //如果有则根据结果进行逻辑处理
                    if (spunlaceOutputDetailDto != null) {
                        //获取检验单状态
                        String checkStatus = spunlaceOutputDetailDto.getCheckStatus();
                        //获取检验单结果
                        String checkResult = spunlaceOutputDetailDto.getCheckResult();

                        //首检未通过：第一个号码检验单状态为“检验完成”，检验单结果“不合格”，物料等级同步检验单据中的判定等级字段；后续号码检验状态为“待检验”，检验单结果为空，物料等级为空
                        if ("2".equals(checkStatus) && "2".equals(checkResult)) {
                            //生成品质检验单，检验状态为待检验
                            //生成品质检验单
                            QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();

                            qualityInspectionDocumentVo.setItemRank(2);//检测阶别：2:Fai
                            qualityInspectionDocumentVo.setInspectionSheetNo(jydj);//检测单号
                            qualityInspectionDocumentVo.setCategory(4);//类别：成品
                            qualityInspectionDocumentVo.setProductionLine(spunlaceOrder.getProductionLine());//线别

                            qualityInspectionDocumentVo.setMaterialCode(spunlaceOrder.getMaterialCode());
                            qualityInspectionDocumentVo.setMaterialCategory(Long.parseLong(spunlaceOutputDto.getMaterialType() + ""));//物料类别
                            qualityInspectionDocumentVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());//批次号

                            qualityInspectionDocumentVo.setAssociatedNo(moNumber);//关联单号
                            qualityInspectionDocumentVo.setDifferentString(spunlaceOrder.getCustomerCode());//客户

                            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<MaterialNumberAndBatchNoVo>();

                            MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                            materialNumberAndBatchNoVo.setMaterialNumber(spunlaceOutputDetail.getProductionNumber());
                            materialNumberAndBatchNoVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());
                            materialNumberAndBatchNoVo.setMaterialCategory(spunlaceOutputDto.getMaterialType());
                            materialNumberAndBatchNoVo.setWsiCustomCode(spunlaceOrder.getCustomerCode());
                            materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                            qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                            qualityFeginService.add(qualityInspectionDocumentVo);

                            //修改水刺明细关联单号，送检标识,检验状态为待检验
                            spunlaceOutputDetail.setIsFlag("1");//检验标识
                            spunlaceOutputDetail.setCheckStatus("1");//待检验
                            spunlaceOutputDetail.setConnectQualityDoc(jydj);
                            spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
                        }

                        if ("2".equals(checkStatus) && "1".equals(checkResult)) {
                            //修改物料等级为良品
                            spunlaceOutputDetail.setMaterielGrade("1");//良品;
                            spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
                        }
                    }
                }*/
                    }
                }
            }
        }
        SpunlaceOrderViewDto viewInfo = getViewInfo(spunlacePrintVo.getId());
        viewInfo.setProductionNumber(mj);
        viewInfo.setCreateMan(SecurityUtils.getUsername());
        viewInfo.setCreateTime(new Date());

        SpunlaceOutputDetail spunlaceOutputDetail = spunlaceOutputDetailMapper.selectOne(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getProductionNumber, mj));
        viewInfo.setGrossWeight(spunlaceOutputDetail.getGrossWeight());
        viewInfo.setNetWeight(String.valueOf(spunlaceOutputDetail.getNetWeight()));
        viewInfo.setBreadth(spunlaceOutputDetail.getBreadth());
        viewInfo.setRollLength(spunlaceOutputDetail.getRollLength());
        viewInfo.setRollingDiameter(spunlaceOutputDetail.getRollingDiameter());
        viewInfo.setGrawWeight(spunlaceOutputDetail.getGrawWeight());
        viewInfo.setThick(spunlaceOutputDetail.getThick());
        viewInfo.setJoint(spunlaceOutputDetail.getJoint());
        viewInfo.setDefect(spunlaceOutputDetail.getDefect());
        viewInfo.setExceptionRemark(spunlaceOutputDetail.getExceptionRemark());
        viewInfo.setProductionBatch(spunlaceOutputDetail.getProductionBatch());

        return viewInfo;
    }

    /**
     * 水刺产出列表
     *
     * @param spunlaceOutputVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    @Transactional(rollbackFor = Exception.class)
    public List<SpunlaceOutputDto> getList(SpunlaceOutputVo spunlaceOutputVo) {
        List<SpunlaceOutputDto> list = spunlaceOutputMapper.getList(spunlaceOutputVo);
        for (SpunlaceOutputDto spunlaceOutputDto : list) {
            //网形
            List<SysDictData> typeArray = DictUtils.getDictCache("sys_of_type");
            Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //铺网类型
            List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
            Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //生产状态
            List<SysDictData> spunlaceArray = DictUtils.getDictCache("spunlace_output_status");
            Map<String, String> spunlaceMap = spunlaceArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            spunlaceOutputDto.setMaterialNetDict(typeMap.get(spunlaceOutputDto.getMaterialNet()));
            spunlaceOutputDto.setMaterialNetTypeDict(netTypeMap.get(spunlaceOutputDto.getMaterialNetType()));
            spunlaceOutputDto.setProductionStatusDict(spunlaceMap.get(spunlaceOutputDto.getProductionStatus()));
        }
        return list;
    }

    /**
     * 扫描入库
     *
     * @param stockInVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockInDto stockIn(StockInVo stockInVo) throws Exception {

        //根据id查出当前水刺产出制令单号
        SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectById(stockInVo.getId());

        SpunlaceOutputDto spunlaceOutputDto = spunlaceOutputMapper.selectViewId(stockInVo.getId());

        //获取制令单号
        String moNumber = spunlaceOutput.getSpunlaceOrderNumber();
        //通过制令单查出水刺指令单
        SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectOne(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getSpunlaceOrderNumber, moNumber));
        //查询当前制令单对应的母卷明细
        SpunlaceOutputDetail spunlaceOutputDetail = spunlaceOutputDetailMapper.selectOne(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getProductionNumber, stockInVo.getProductionNumber()).eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, moNumber));
        if (spunlaceOutputDetail == null) {
            throw new GlobalException("入库失败，请确认条码无误后重新扫描");
        }

        if (!"1".equals(spunlaceOutputDetail.getProductionStatus())) {
            throw new GlobalException("此产品已入库");
        }

        //修改水刺产出明细为已入库
        spunlaceOutputDetail.setProductionStatus("2");
        spunlaceOutputDetail.setStockMan(SecurityUtils.getUsername());
        spunlaceOutputDetail.setStockDate(new Date());
        boolean b = spunlaceOutputDetailService.updateById(spunlaceOutputDetail);

        StockInDto stockInDto = new StockInDto();
        if (b) {
            Integer output = spunlaceOutput.getOutput();
            if (output == null) {
                output = 0;
            }
            //回传水刺产出数量和重量
            spunlaceOutput.setOutput(output + 1);

            Double outputWeight = spunlaceOutput.getOutputWeight();
            if (outputWeight == null) {
                outputWeight = 0.0;
            }

            BigDecimal bigDecimal = new BigDecimal(String.valueOf(outputWeight));
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(spunlaceOutputDetail.getNetWeight()));
            spunlaceOutput.setOutputWeight((bigDecimal.add(bigDecimal1)).doubleValue());
            updateById(spunlaceOutput);

            //回传水刺产出（良品产出重量）
            spunlaceOrder.setGoodOutweight((bigDecimal.add(bigDecimal1)).doubleValue());
            spunlaceOrderService.updateById(spunlaceOrder);

            //回传水刺良品重量到排程
            BackWeight backWeight = new BackWeight();
            backWeight.setProductionSpinyWeight(spunlaceOutputDetail.getNetWeight());
            backWeight.setPlanCode(spunlaceOrder.getProductionPlanNumber());
            AjaxResult ajaxResult = schedulingPlanFeignService.planBack(backWeight);

            if (ajaxResult == null) {
                throw new GlobalException("入库失败");
            }


            //完工入库部分
            WipOtherAddVo wipOtherAddVo = new WipOtherAddVo();
            wipOtherAddVo.setMakingOrderNo(spunlaceOutputDetail.getSpunlaceOrderNumber());//制令单号
            wipOtherAddVo.setWarehousTime(new Date());//入库日期
            wipOtherAddVo.setMaterialCode(spunlaceOutput.getMaterialCode());//物料编码
            wipOtherAddVo.setMaterialCategory(4);
            wipOtherAddVo.setPlannedWeight(spunlaceOrder.getPlanWeight());//计划重量
            wipOtherAddVo.setWarehousingNum(1);
            wipOtherAddVo.setDocumentType(12);
            wipOtherAddVo.setReceiveType(2);
            wipOtherAddVo.setGenerationMethod(2);
            wipOtherAddVo.setMaterialNumber(spunlaceOutputDetail.getProductionNumber());
            wipOtherAddVo.setGrossWeight(spunlaceOutputDetail.getGrossWeight());
            wipOtherAddVo.setNetWeight(spunlaceOutputDetail.getNetWeight());
            wipOtherAddVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());

            String replace = moNumber.replace("SC", "FQ");
            //查询分切制令单状态
            CutOrdersDocument cutOrdersDocument1 = cutOrdersDocumentMapper.selectOne(new QueryWrapper<CutOrdersDocument>().lambda().eq(CutOrdersDocument::getSplittingOrderNumber, replace));


            //生成完工入库单
            storageFegin.wipOtherAdd(wipOtherAddVo);
            //生成分切明细
            CutOrdersDocumentDetailVo cutOrdersDocumentDetailVo = new CutOrdersDocumentDetailVo();


            cutOrdersDocumentDetailVo.setDocumentNum(replace);//制令单号
            cutOrdersDocumentDetailVo.setMasterVolumeNum(spunlaceOutputDetail.getProductionNumber());//母卷号码
            cutOrdersDocumentDetailVo.setMaterialCode(spunlaceOutput.getMaterialCode());//产品编码
            if (spunlaceOutputDetail.getMaterielGrade() != null) {
                cutOrdersDocumentDetailVo.setMaterialLevel(Integer.parseInt(spunlaceOutputDetail.getMaterielGrade()));//物料等级
            }
            cutOrdersDocumentDetailVo.setProductNumber(spunlaceOutputDetail.getProductionNumber());//母卷号码
            cutOrdersDocumentDetailVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());//批次号

            if (cutOrdersDocument1.getWhetherExemption() == 1) {
                cutOrdersDocumentDetailVo.setClothInspectionStatus(2);//验布状态
            } else {
                cutOrdersDocumentDetailVo.setClothInspectionStatus(1);//验布状态
            }


            cutOrdersDocumentDetailVo.setSlittingStatus(1);//分切状态
            cutOrdersDocumentDetailVo.setWidth(spunlaceOutputDetail.getBreadth());//幅宽
            cutOrdersDocumentDetailVo.setRollDiameter(spunlaceOutputDetail.getRollingDiameter());//卷径
            cutOrdersDocumentDetailVo.setGramWeight(spunlaceOutputDetail.getGrawWeight());//克重
            cutOrdersDocumentDetailVo.setThickness(spunlaceOutputDetail.getThick());//厚度
            cutOrdersDocumentDetailVo.setJoint(spunlaceOutputDetail.getJoint());//接头
            cutOrdersDocumentDetailVo.setClassDifference(spunlaceOutputDetail.getClasses());//班别
            cutOrdersDocumentDetailVo.setRollLength(spunlaceOutputDetail.getRollLength());//长度
            cutOrdersDocumentDetailVo.setSmallRollWeight(spunlaceOutputDetail.getNetWeight());//净重
            cutOrdersDocumentDetailService.add(cutOrdersDocumentDetailVo);

            //回传分切母卷数量
            CutOrdersDocument cutOrdersDocument = cutOrdersDocumentMapper.selectOne(new QueryWrapper<CutOrdersDocument>().lambda().eq(CutOrdersDocument::getSplittingOrderNumber, replace));
            Integer masterRollNum = cutOrdersDocument.getMasterRollNum();
            if (masterRollNum == null) {
                masterRollNum = 0;
            }
            cutOrdersDocument.setMasterRollNum(masterRollNum + 1);
            cutOrdersDocumentService.updateById(cutOrdersDocument);

            String jydj = "FAI-" + feignService.splitList("JYDJ");

            //首检
            //获取菜单id
            Long menuId = feignService.getIdByMenuName("水刺产出");
            //交接方式
            AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
            if (infoDocumentConfigById != null) {
                SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);

                if (sysDocument.getDocInspectionMark() == 1) {
                    //获取品质检验配置明细
                    List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();

                    List<SysDocumentCheckDto> documentCheckDtos1 = new ArrayList<SysDocumentCheckDto>();
                    for (SysDocumentCheckDto sysDocumentCheckDto : documentCheckDtoList) {
                        if (sysDocumentCheckDto.getCheckSubmit() == 2 && sysDocumentCheckDto.getCheckType() == 4) {
                            documentCheckDtos1.add(sysDocumentCheckDto);
                        }
                    }
                    if (documentCheckDtoList.size() == 0) {
                        throw new GlobalException("请先配置送检类型");
                    }


                    for (SysDocumentCheckDto sysDocumentCheckDto : documentCheckDtos1) {


                        //如果是首检
                        if (sysDocumentCheckDto.getCheckMode() == 1) {

                            if ("1".equals(spunlaceOutputDetail.getFirstNum())) {
                                //生成首检单
                                QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();

                                qualityInspectionDocumentVo.setItemRank(2);//检测阶别：2:Fai
                                qualityInspectionDocumentVo.setInspectionSheetNo(jydj);//检测单号
                                qualityInspectionDocumentVo.setCategory(4);//类别：成品
                                qualityInspectionDocumentVo.setProductionLine(spunlaceOrder.getProductionLine());//线别

                                qualityInspectionDocumentVo.setMaterialCode(spunlaceOrder.getMaterialCode());
                                qualityInspectionDocumentVo.setMaterialCategory(Long.parseLong(spunlaceOutputDto.getMaterialType() + ""));//物料类别
                                qualityInspectionDocumentVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());//批次号

                                qualityInspectionDocumentVo.setAssociatedNo(moNumber);//关联单号
                                qualityInspectionDocumentVo.setDifferentString(spunlaceOrder.getCustomerCode());//客户
                                qualityInspectionDocumentVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());

                                qualityInspectionDocumentVo.setClasses(spunlaceOutputDetail.getClasses());//班次
                                qualityInspectionDocumentVo.setGroupCode(spunlaceOutputDetail.getGroupCode());//班组
                                qualityInspectionDocumentVo.setCrossSkyTime(spunlaceOutputDetail.getCrossSkyTime());//跨天时间
                                qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                qualityInspectionDocumentVo.setModeType(9);


                                List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<MaterialNumberAndBatchNoVo>();

                                MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                materialNumberAndBatchNoVo.setMaterialNumber(spunlaceOutputDetail.getProductionNumber());
                                materialNumberAndBatchNoVo.setBatchNo(spunlaceOutputDetail.getProductionBatch());
                                materialNumberAndBatchNoVo.setMaterialCategory(spunlaceOutputDto.getMaterialType());
                                materialNumberAndBatchNoVo.setWsiCustomCode(spunlaceOrder.getCustomerCode());
                                materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);

                                qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                                qualityFeginService.add(qualityInspectionDocumentVo);

                                //修改水刺明细关联单号，送检标识,检验状态为待检验
                                spunlaceOutputDetail.setIsFlag("1");//检验标识
                                spunlaceOutputDetail.setCheckStatus("1");//待检验
                                spunlaceOutputDetail.setConnectQualityDoc(jydj);
                                spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
                            }

                            //查询最近一条品质检验单号并且有检验标识
                            SpunlaceOutputDetailDto spunlaceOutputDetailDto = spunlaceOutputDetailMapper.selectQuality(moNumber);
                            //如果有则根据结果进行逻辑处理
                            if (spunlaceOutputDetailDto != null) {
                                //获取检验单状态
                                String checkStatus = spunlaceOutputDetailDto.getCheckStatus();
                                //获取检验单结果
                                String checkResult = spunlaceOutputDetailDto.getCheckResult();

                                //首检未通过：第一个号码检验单状态为“检验完成”，检验单结果“不合格”，物料等级同步检验单据中的判定等级字段；后续号码检验状态为“待检验”，检验单结果为空，物料等级为空
                                if ("2".equals(checkStatus) && "2".equals(checkResult)) {
                                    //生成品质检验单，检验状态为待检验
                                    //生成品质检验单

                                    //查询品质检验单状态为不合格的下一条母卷信息
                                    SpunlaceOutputDetail defects = spunlaceOutputDetailMapper.selectDefects(spunlaceOutputDetailDto.getSpunlaceOrderNumber());

                                    QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();

                                    qualityInspectionDocumentVo.setItemRank(2);//检测阶别：2:Fai
                                    qualityInspectionDocumentVo.setInspectionSheetNo(jydj);//检测单号
                                    qualityInspectionDocumentVo.setCategory(4);//类别：成品
                                    qualityInspectionDocumentVo.setProductionLine(spunlaceOrder.getProductionLine());//线别

                                    qualityInspectionDocumentVo.setMaterialCode(spunlaceOrder.getMaterialCode());
                                    qualityInspectionDocumentVo.setMaterialCategory(Long.parseLong(spunlaceOutputDto.getMaterialType() + ""));//物料类别
                                    qualityInspectionDocumentVo.setBatchNo(defects.getProductionBatch());//批次号

                                    qualityInspectionDocumentVo.setAssociatedNo(moNumber);//关联单号
                                    qualityInspectionDocumentVo.setDifferentString(spunlaceOrder.getCustomerCode());//客户

                                    qualityInspectionDocumentVo.setClasses(defects.getClasses());//班次
                                    qualityInspectionDocumentVo.setGroupCode(defects.getGroupCode());//班组
                                    qualityInspectionDocumentVo.setCrossSkyTime(defects.getCrossSkyTime());//跨天时间

                                    qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                    qualityInspectionDocumentVo.setModeType(9);

                                    List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<MaterialNumberAndBatchNoVo>();

                                    MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                    materialNumberAndBatchNoVo.setMaterialNumber(defects.getProductionNumber());
                                    materialNumberAndBatchNoVo.setBatchNo(defects.getProductionBatch());
                                    materialNumberAndBatchNoVo.setMaterialCategory(spunlaceOutputDto.getMaterialType());
                                    materialNumberAndBatchNoVo.setWsiCustomCode(spunlaceOrder.getCustomerCode());
                                    materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                    qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                                    qualityFeginService.add(qualityInspectionDocumentVo);

                                    //修改水刺明细关联单号，送检标识,检验状态为待检验
                                    defects.setIsFlag("1");//检验标识
                                    defects.setCheckStatus("1");//待检验
                                    defects.setConnectQualityDoc(jydj);
                                    spunlaceOutputDetailService.updateById(defects);
                                }

                                if ("2".equals(checkStatus) && "1".equals(checkResult)) {
                                    //修改物料等级为良品
                                    spunlaceOutputDetail.setMaterielGrade("1");//良品;
                                    spunlaceOutputDetailService.updateById(spunlaceOutputDetail);
                                }
                            }
                        }
                    }
                }
            }
            //获取车间建模下绑定的车间
//            SysShopModelingDto warehouseing = sysShopModelingMapper.getWarehouseing(spunlaceOutput.getWorkshop());
//            //获取车间
//            Long id = warehouseing.getModelingBindingStorage();
//            //车间
//            AjaxResult view = storageFegin.view(id);
//            WarehouseDto warehouseDto = JSON.parseObject(JSON.toJSONString(view.get("data")), WarehouseDto.class);

            //产出明细入库存
            WmsStockInfoVo wmsStockInfoVo = new WmsStockInfoVo();
            wmsStockInfoVo.setWsiMaterialNumber(spunlaceOutputDetail.getProductionNumber());//物料号码
            wmsStockInfoVo.setWsiCategory("4");//类别(1是原料2是辅料3是半成品4是成品)
            wmsStockInfoVo.setWsiMaterialCode(spunlaceOutput.getMaterialCode());//物料编码
            wmsStockInfoVo.setWsiMaterialNum(1);//物料数量
            wmsStockInfoVo.setWsiMaterialStatus(2);//库存状态
            wmsStockInfoVo.setWsiMaterialGrade(spunlaceOutputDetail.getMaterielGrade());//物料等级
            wmsStockInfoVo.setWsiMaterialBatch(spunlaceOutputDetail.getProductionBatch());//批次号
            wmsStockInfoVo.setWsiGorssWeight(spunlaceOutputDetail.getGrossWeight());//毛重
            wmsStockInfoVo.setWsiNetWeight(spunlaceOutputDetail.getNetWeight());//净重
            //wmsStockInfoVo.setWsiWarehourse(warehouseDto.getWarehouseCode());//仓库
            wmsStockInfoVo.setWsiCustomCode(spunlaceOutput.getCustomerCode());//客户编码
            wmsStockInfoVo.setWsiConnectNum(spunlaceOutputDetail.getSpunlaceOrderNumber());//关联单号
            wmsStockInfoVo.setCreateUser(SecurityUtils.getUsername());//创建人
            wmsStockInfoVo.setWsiLength(Double.parseDouble(spunlaceOutputDetail.getRollLength()));//长度
            wmsStockInfoVo.setWsiDiameter(spunlaceOutputDetail.getRollingDiameter());//卷径
            wmsStockInfoVo.setWsiGrawWeight(spunlaceOutputDetail.getGrawWeight());//克重
            wmsStockInfoVo.setWsiThick(spunlaceOutputDetail.getThick());//厚度
            wmsStockInfoVo.setWsiJoint(spunlaceOutputDetail.getJoint());//接头
            wmsStockInfoVo.setWsiWidth(spunlaceOutputDetail.getBreadth());//幅宽
            wmsStockInfoVo.setWsiProducedStep("2");//生产阶别（水刺）
            wmsStockInfoVo.setWsiProducedDate(new Date());//生产日期
            wmsStockInfoVo.setWsiReveiveTime(new Date());//入库日期

            storageFegin.addWmsStock(wmsStockInfoVo);
            stockInDto.setMessage("物料号码:" + spunlaceOutputDetail.getProductionNumber() + "，净重" + spunlaceOutputDetail.getNetWeight() + ",物料名称：" + spunlaceOutputDto.getMaterialName() + "入库成功");
        } else {
            throw new GlobalException("入库失败");
        }

        return stockInDto;
    }

    /**
     * 废料打印
     *
     * @param spunlaceWasteVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SpunlaceWasteVo wastePrint(SpunlaceWasteVo spunlaceWasteVo) throws Exception {
        WasteTube wasteTube = new WasteTube();
        BeanUtils.copyProperties(spunlaceWasteVo, wasteTube);
        wasteTube.setWasteType(2);//水刺类别
        wasteTube.setFeedOrderNumber(spunlaceWasteVo.getSpunlaceOrderNumber());
        String authorityCoding = feignService.getAuthorityCoding("productionTube:prostatistics:wastemanage:list");
        if (authorityCoding == null) {
            throw new GlobalException("未进行单据配置,单据编码生成失败");
        }
        wasteTube.setWasteScrapNumber(authorityCoding);
        wasteTube.setLineCode(spunlaceWasteVo.getProductionLineCode());
        wasteTube.setPrinterBy(SecurityUtils.getUsername());
        wasteTube.setPrinterTime(new Date());
        int i = iWasteTubeService.insertWasteTube(wasteTube);
        if (i == 0) {
            throw new GlobalException("打印失败");
        }

        spunlaceWasteVo.setPrintBy(SecurityUtils.getUsername());
        spunlaceWasteVo.setPrintTime(new Date());
        spunlaceWasteVo.setWsproductionNumber(authorityCoding);
        spunlaceWasteVo.setProductionLevel("水刺");
        return spunlaceWasteVo;
    }

    /**
     * 单据完成
     *
     * @param spunlaceOutputVo
     * @return
     */
    @Override
    public boolean finish(SpunlaceOutputVo spunlaceOutputVo) {
        SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectById(spunlaceOutputVo.getId());
        if (!"1".equals(spunlaceOutput.getProductionStatus())) {
            throw new GlobalException("只能对生产中的单据进行操作");
        }
        //查询当前制令单下的明细状态为待入库的
        long aLong = spunlaceOutputDetailMapper.selectCount(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, spunlaceOutput.getSpunlaceOrderNumber()).eq(SpunlaceOutputDetail::getProductionStatus, 1));
        if (aLong > 0) {
            throw new GlobalException("存在未入库产品,不能单据完成");
        }
        //查询计划重量
        SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectOne(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getSpunlaceOrderNumber, spunlaceOutput.getSpunlaceOrderNumber()));
        if (spunlaceOrder.getPlanWeight() > spunlaceOutput.getOutputWeight()) {
            throw new GlobalException("当前制令单没有达到计划重量,无法单据完成");
        }
        spunlaceOutput.setProductionStatus("4");
        boolean b = updateById(spunlaceOutput);

        if (b) {
            spunlaceOrder.setDocumentStatus("8");
            spunlaceOrderService.updateById(spunlaceOrder);

            //回传排程实际开工时间
            BackAdjustVo backAdjustVo = new BackAdjustVo();
            backAdjustVo.setExecutionState(6);//已完成
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            backAdjustVo.setActualEndTime(simpleDateFormat.format(new Date()));
            backAdjustVo.setExecutionDoc(spunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));


            AjaxResult ajaxResult = schedulingPlanFeignService.backAdjust(backAdjustVo);
            if ("500".equals(ajaxResult.get("code"))) {
                throw new GlobalException("完成失败");
            }

            //查询预计开工时间最近的线别下的制令单
            //查询当前线别下，待上线，并且开工时间最近的指令单
            SpunlaceOrder byTime = spunlaceOrderMapper.getByTime(spunlaceOrder.getProductionLine());
            if (byTime != null) {
                SpunlaceOrder timeSpunlaceOrder = spunlaceOrderMapper.selectById(byTime.getId());
                if (timeSpunlaceOrder != null) {
                    //修改为生产中
                    timeSpunlaceOrder.setDocumentStatus("1");

                    FeedRecord feedRecord = new FeedRecord();

                    feedRecord.setFeedOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());
                    feedRecord.setLineCode(timeSpunlaceOrder.getProductionLine());
                    feedRecord.setMaterialCode(timeSpunlaceOrder.getMaterialCode());

                    if (timeSpunlaceOrder.getBomWeight()!=null){
                        feedRecord.setDeliveryWeight(Double.parseDouble(timeSpunlaceOrder.getBomWeight()));
                    }


                    feedRecord.setCreateBy(SecurityUtils.getUsername());
                    feedRecord.setFeedType("1");

                    MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, timeSpunlaceOrder.getMaterialCode()));

                    feedRecord.setMaterialName(materialFinished.getMaterialName());
                    feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());

                    iFeedRecordService.insertFeedRecord(feedRecord);


                    timeSpunlaceOrder.setActualStartTime(new Date());

                    spunlaceOrderService.updateById(timeSpunlaceOrder);

                    //回传排程实际开工时间
                    BackAdjustVo backAdjustVo1 = new BackAdjustVo();

                    backAdjustVo1.setActualStartTime(simpleDateFormat.format(new Date()));
                    backAdjustVo1.setExecutionDoc(timeSpunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                    backAdjustVo1.setExecutionState(3);//生产中

                    AjaxResult ajaxResult1 = schedulingPlanFeignService.backAdjust(backAdjustVo1);
                    if ("500".equals(ajaxResult1.get("code").toString())) {
                        throw new GlobalException("单据完成失败");
                    }

                    //查询水刺产出是否存在单据
                    SpunlaceOutput spunlaceOutput1 = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, timeSpunlaceOrder.getSpunlaceOrderNumber()));

                    if (spunlaceOutput1 == null) {
                        //水刺产出列表上线
                        SpunlaceOutputVo spunlaceOutputVo1 = new SpunlaceOutputVo();

                        spunlaceOutputVo1.setProductionLine(timeSpunlaceOrder.getProductionLine());//生产线别
                        spunlaceOutputVo1.setWorkshop(timeSpunlaceOrder.getWorkshop());
                        spunlaceOutputVo1.setSpunlaceOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());//制令单号
                        spunlaceOutputVo1.setProductionStatus("1");//生产状态  生产中
                        spunlaceOutputVo1.setMaterialCode(timeSpunlaceOrder.getMaterialCode());//物料编码
                        spunlaceOutputVo1.setMotherBreadth(timeSpunlaceOrder.getMotherBreadth());//母卷幅宽
                        spunlaceOutputVo1.setRollingDiameter(timeSpunlaceOrder.getRollingDiameter());//卷径
                        spunlaceOutputVo1.setThick(timeSpunlaceOrder.getThick());
                        spunlaceOutputVo1.setProductionPlanNumber(timeSpunlaceOrder.getProductionPlanNumber());//生产计划单号
                        spunlaceOutputVo1.setPlanWeight(timeSpunlaceOrder.getPlanWeight());
                        add(spunlaceOutputVo1);

                    } else {
                        spunlaceOutput1.setProductionStatus("1");
                        updateById(spunlaceOutput1);
                    }


            }
        }

            //当该计划单对应的水刺制令单全为完成或者关结时修改
            String productionPlanNumber = spunlaceOrder.getProductionPlanNumber();
            //通过计划单号，判断是否是合并单
            String[] split = productionPlanNumber.split(",");

            //定义所有水刺制令单完成或者关结的标志
            boolean flag = true;


            for (String planNumber : split) {
                //查出计划单对应的所有水刺制令单
                List<SpunlaceOrder> spunlaceOrderList = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getProductionPlanNumber, planNumber));

                for (SpunlaceOrder order : spunlaceOrderList) {
                    //如果不为已完成或者已关结修改标志为false
                    if (!"8".equals(order.getDocumentStatus()) && !"9".equals(order.getDocumentStatus())) {
                        flag = false;
                        break;
                    }
                }

                //查出计划单对应的所有分切制令单
                List<CutOrdersDocument> cutOrdersDocumentList = spunlaceOrderMapper.getFqInfo(planNumber);

                if (flag) {

                    for (CutOrdersDocument cutOrdersDocument : cutOrdersDocumentList) {
                        if (4 != cutOrdersDocument.getProductStatus() && 5 != cutOrdersDocument.getProductStatus()) {
                            flag = false;
                            break;
                        }
                    }
                }
            }


            if (flag) {
                BackWeight backWeight = new BackWeight();
                backWeight.setPlanCode(productionPlanNumber);
                //修改排程单和排程计划单状态为已完成
                schedulingPlanFeignService.updatePlanFinishStatus(backWeight);
            }
        }
        return b;
    }

    /**
     * 水刺产出查看
     *
     * @param id
     * @return
     */
    @Override
    public SpunlaceOrderViewDto getViewInfo(Long id) {
        //查出当前的水刺产出信息
        SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectById(id);
        //查出水刺制令单id
        SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectOne(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getSpunlaceOrderNumber, spunlaceOutput.getSpunlaceOrderNumber()));
        SpunlaceOrderViewDto view = spunlaceOrderService.view(spunlaceOrder.getId());
        view.setId(id);
        SysShopModeling sysShopModeling = sysShopModelingMapper.selectOne(new QueryWrapper<SysShopModeling>().lambda().eq(SysShopModeling::getModelingCode, spunlaceOutput.getProductionLine()));
        view.setProductionLineCode(spunlaceOutput.getProductionLine());
        view.setProductionLine(sysShopModeling.getModelingName());
        return view;
    }

    /**
     * 产出统计
     *
     * @param moNumber
     * @return
     */
    @Override
    public List<OutputStaticDto> outputStatic(String moNumber) {
        SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, moNumber));
        if ("1".equals(spunlaceOutput.getProductionStatus())) {
            List<OutputStaticDto> outputStaticDtos = spunlaceOutputMapper.outputStatic(moNumber);
            for (OutputStaticDto outputStaticDto : outputStaticDtos) {
                List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
                Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                outputStaticDto.setClasses(classMap.get(outputStaticDto.getClasses()));
            }
            return outputStaticDtos;
        } else {
            throw new GlobalException("只能查看生产中的数据");
        }
    }
}
